<?php

namespace app\api\controller;

use app\common\controller\Api;
use think\Db;
use think\Exception;

/**
 * 示例接口
 */
class Outh extends Api
{


    protected $noNeedLogin = ['test', 'test1','buy_update','homeBusiness','jp_content','busDetail','business_list','banner_shop','gd_contents','contend_detail','search'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // 商家详情
    public function business_detail()
    {

        $result = Db::name('user_business')->where('id',$this->auth->shop_id)->field('id,avatar,num,name,notice,mobile,position,content,imgdetail,status,memo,code,position,detail,license_image,company_image,banner_image')->find();


        $end_time = date('Y-m-d ',$this->auth->end_time);
        $result['end_time']  = $end_time.' 到期';
        $this->success('商家详情',$result);
    }


    // 管理商家
    public function manage_business()
    {
        $avatar = $this->request->post('avatar');
        $name = $this->request->post('name');
        $mobile = $this->request->post('mobile');
        $position = $this->request->post('position');
        $content = $this->request->post('content');
        $imgdetail = $this->request->post('imgdetail');
        $banner_image = $this->request->post('banner_image');
        if (!$avatar or !$name or !$mobile or !$position or !$content)
        {
            $this->error('缺少参数');
        }
        Db::name('user_business')->where('id',$this->auth->shop_id)->update(['avatar'=>$avatar,'banner_image'=>$banner_image,'imgdetail'=>$imgdetail,'name'=>$name,'mobile'=>$mobile,'position'=>$position,'content'=>$content]);
        $this->success('更新成功',1);
    }

    // 列表
    public function business_list()
    {

        $address = $this->request->header()['address'];
        $provincial_id = get_provincial($address);

        if ($this->auth->id)
        {
            Db::name('user')->where('id',$this->auth->id)->update(['provincial_id'=>$provincial_id]);
        }
        $result  = Db::name('user_business')->where(['status'=>'1','is_status'=>'1','provincial_id'=>$provincial_id])
            ->order('is_s_top desc,updatetime desc')
            ->field('id,avatar,mobile,position,name,content,latitude,longitude');
        $result = api_page($result);

        foreach ($result as $key=>$value)
        {
            if (empty($value['mobile']))
            {
                $result[$key]['mobile'] = '';
            }

            if (empty($value['content']))
            {
                $result[$key]['content'] = '';
            }
            if (!$this->auth->lat or  !$value['latitude'])
            {
                $result[$key]['km'] = '';
            }else{
                $result[$key]['km'] = $this->GetDistance($this->auth->lat,$this->auth->lng,$value['latitude'],$value['longitude'],2).'km';

            }

        }
        $this->success('成功',$result);
    }


    /**
     * 计算两组经纬度坐标 之间的距离
     * params ：lat1 纬度1； lng1 经度1； lat2 纬度2； lng2 经度2； len_type （1:m or 2:km);
     * return m or km
     */
    public function GetDistance($lat1, $lng1, $lat2, $lng2, $len_type = 1, $decimal = 2) {

        $radLat1 = $lat1 * PI / 180.0;
        $radLat2 = $lat2 * PI / 180.0;
        $a = $radLat1 - $radLat2;
        $b = ($lng1 * PI / 180.0) - ($lng2 * PI / 180.0);
        $s = 2 * asin(sqrt(pow(sin($a/2),2) + cos($radLat1) * cos($radLat2) * pow(sin($b/2),2)));
        $s = $s * EARTH_RADIUS;
        $s = round($s * 1000);
        if ($len_type > 1)
        {
            $s /= 1000;
        }
        return round($s, $decimal);
    }



    public function banner_shop()
    {
        $address = $this->request->header()['address'];
        get_provincial($address);
        $result = Db::name('banners_shop')->where('ex_status','1')->where('provincial_id',get_provincial($address))->where('status',1)->field('id,image,type_url,type_id,type,type_id')->select();

        $this->success('返回成功',$result);
    }
    // 精品推荐
    public function jp_content()
    {
        $search = $this->request->post('name');
//        $is_status = $this->request->post('is_status','0');// 1=在售,0=待上架
//        $where['a.is_status'] = $is_status==1?'0':'1';
        $where = [];
        if ($search)
        {
            $where['a.name']=['like',"%{$search}%"];
//            $where['desc']=['like',"%{$search}%"];
        }
//        halt($where);
        $result = Db::name('shop')
            ->alias('a')
            ->join('shop_type b','a.shop_type_id=b.id')
//            ->where('status',2)
            ->where($where)
            ->where('a.status','1')
            ->where('a.is_status','1')
            ->where('a.is_g_top','1')
//            ->where('a.user_id',$this->auth->id)
            ->order('a.updatetime desc')
            ->field('a.id,a.image,a.name,b.name as type_name,a.price,a.num,a.status')
            ->select()
        ;

//        $result = api_page($result);
        foreach ($result as $key =>$value)
        {
            $result[$key]['status_text'] = $value['status']==0?'待审核':(1?'审核成功':'审核失败');
        }
        $this->success('成功',$result);
    }

    // 精品推荐->更多
    public function gd_contents()
    {
        $search = $this->request->post('name');
//        $is_status = $this->request->post('is_status','0');// 1=在售,0=待上架
//        $where['a.is_status'] = $is_status==1?'0':'1';
        $where = [];
//        if ($search)
//        {
//            $where['a.name']=['like',"%{$search}%"];
////            $where['desc']=['like',"%{$search}%"];
//        }
//        halt($where);
        $address = $this->request->header()['address'];
        $provincial_id = get_provincial($address);

        $result = Db::name('shop')
            ->alias('a')
            ->join('shop_type b','a.shop_type_id=b.id')
//            ->where('status',2)
            ->where($where)
            ->where('a.status','1')
            ->where('a.is_status','1')
            ->where('a.provincial_id',$provincial_id)
            ->order('a.is_s_top desc,a.updatetime desc')
            ->field('a.id,a.image,a.name,b.name as type_name,a.price,a.num,a.status')
        ;

        $result = api_page($result);
        foreach ($result as $key =>$value)
        {
            $result[$key]['status_text'] = $value['status']==0?'待审核':(1?'审核成功':'审核失败');
        }
        $this->success('成功',$result);
    }
    public function search()
    {
        $type = $this->request->post('type'); //1=商家 2=商品
        $search= $this->request->post('search'); //1=商家 2=商品
        $where = [];

        if ($type==1)
        {
            if ($search)
            {
                $where['name']=['like',"%{$search}%"];
            }
            $result  = Db::name('user_business')
                ->where($where)
                ->where(['status'=>'1','is_status'=>'1'])
                ->order('updatetime desc')
                ->field('id,avatar,mobile,position,name,content,latitude,longitude')
                ->select();
            foreach ($result as $key=>$value)
            {
                if (empty($value['mobile']))
                {
                    $result[$key]['mobile'] = '';
                }
                if (!$this->auth->lat or  !$value['latitude'])
                {
                    $result[$key]['km'] = '';
                }else{
                    $result[$key]['km'] = $this->GetDistance($this->auth->lat,$this->auth->lng,$value['latitude'],$value['longitude'],2).'km';

                }
            }
            $this->success('成功',$result);
        }else{

            $where = [];
            if ($search)
            {
                $where['a.name']=['like',"%{$search}%"];
            }
            $result = Db::name('shop')
                ->alias('a')
                ->join('shop_type b','a.shop_type_id=b.id')
//            ->where('status',2)
                ->where($where)
                ->where('a.status','1')
                ->where('a.is_status','1')
                ->order('a.updatetime desc')
                ->field('a.id,a.image,a.name,b.name as type_name,a.price,a.num,a.status')
                ->select();
            $this->success('成功',$result);

        }
    }

    // 推荐详情
    public function contend_detail()
    {
        $id = $this->request->post('id');
        if (!$id)
        {
            $this->error('缺少参数');
        }
        $result =  Db::name('shop')->where('id',$id)->find();

        $image = explode(',',$result['banner_image']);
        $data = [];
        foreach ($image as $value)
        {
            $data[] = ['image'=>$value];
        }
        $result['banner_image'] = $data;
        $result['type_name'] = Db::name('shop_type')->where('id',$result['shop_type_id'])->value('name');
        $result['detail_image'] = explode(',',$result['detail_image']);
        Db::name('shop')->where('id',$id)->setInc('browse_num');
        $this->success('详情',$result);

    }

    // 获取商家置顶金额列表
    public function getTopMoneyList()
    {
        $type = $this->request->post('type');
        if ($type==2)
        {
            $result1 = Db::name('topping_business')->where('city_type',1)->where('type',1)->field('id,name,price')->select();

        }else{
            $result1 = Db::name('topping_business')->where('city_type',2)->where('type',1)->field('id,name,price')->select();

        }
        foreach ($result1 as $key => $value)
        {
            $result1[$key]['aaa'] = false;
        }
        $this->success('成功',$result1);
    }
    // 获取置顶金额
    public function getTopMoney()
    {
        $top_id     = $this->request->param('top_id');
        if (!$top_id)
        {
            $this->error('请先选择购买期限');
        }
        $type     = $this->request->param('type'); // 1= 微信支付,2=积分支付,3=混合支付
        if (!$type)
        {
            $this->error('缺少参数');
        }
        $result = Db::name('topping_business')->where('id',$top_id)->find();
        if (!$result){
            $this->error('系统出错');
        }


        // 积分兑换比例
        $refresh2 = Db::name('config')->where('id',26)->value('value');
        if ($result['city_type']=='1')
        {
            $num = Db::name('config')->where('id',34)->value('value');
            $count = Db::name('user_business')->where('is_g_top',1)->count();
            if ($count >=$num)
            {
                $this->error('置顶位置不足');
            }
            if ($type=='1')
            {
                $money = $result['price'];
                $this->success('',['money'=>$money,'score'=>0]);
            }elseif($type=='2'){
                $score = $result['price'] * $refresh2;
                if ($score > $this->auth->score)
                {
                    $this->success('','积分不足');
                }
                $this->success('',['money'=>0,'score'=>$score]);
            }else{
                $score =  $result['price'] /2 *  $refresh2;
                $money =  $result['price'] /2;
                if ($this->auth->score < $score)
                {
                    $this->error('积分不足');
                }
                $this->success('',['money'=>$money,'score'=>$score]);
            }

        }elseif ($result['city_type']=='2')
        {

            $num = Db::name('config')->where('id',35)->value('value');

            $count = Db::name('user_business')->where('is_s_top',1)->count();

            if ($count >=$num)
            {
                $this->error('置顶位置不足');
            }
            if ($type=='1')
            {
                $money = $result['price'];
                $this->success('成功',['money'=>$money,'score'=>0]);
            }elseif($type=='2'){
                $score = $result['price'] * $refresh2;
                if ($score > $this->auth->score)
                {
                    $this->success('成功','积分不足');
                }
                $this->success('成功',['money'=>0,'score'=>$score]);
            }else{
                $score =  $result['price'] /2 *  $refresh2;
                $money =  $result['price'] /2;
                if ($this->auth->score < $score)
                {
                    $this->error('积分不足');
                }
                $this->success('成功',['money'=>$money,'score'=>$score]);
            }
        }
    }


    // 置顶
    public function businessTop()
    {
        $top_id     = $this->request->param('top_id');
        if (!$top_id)
        {
            $this->error('请先选择购买期限');
        }
        $article_id = $this->auth->shop_id;
        $type = $this->request->param('type');
        if (!$type)
        {
            $this->error('缺少参数');
        }
        $result = Db::name('topping_business')->where('id',$top_id)->find();
        if (!$result){
            $this->error('系统出错');
        }
        $end_time = $result['num']* 86400;
        $article = Db::name('user_business')->where('id',$article_id)->find();
        $update = [];
        Db::startTrans();
        try {
            // 积分兑换比例
            $refresh2 = Db::name('config')->where('id',26)->value('value');
            if ($result['city_type']=='1')
            {
                $num = Db::name('config')->where('id',34)->value('value');

                $count = Db::name('user_business')->where('is_g_top',1)->count();

                if ($count >=$num)
                {
                    $this->error('置顶位置不足');
                }
                if ($type=='1')
                {
                    $money = $result['price'];
                    $this->error('暂未开放');
                }elseif($type=='2'){
                    $score = $result['price'] * $refresh2;
                    if ($score > $this->auth->score)
                    {
                        $this->success('成功','积分不足');
                    }
                    Db::name('user')->where('id',$this->auth->id)->setDec('score',$score);
                }else{
                    $score =  $result['price'] /2 *  $refresh2;
                    $money =  $result['price'] /2;
                    if ($this->auth->score < $score)
                    {
                        $this->error('积分不足');
                    }
                    $this->error('暂未开放');

                    Db::name('user')->where('id',$this->auth->id)->setDec('score',$score);
                }
                if ($article['g_endtime'] != 0)
                {
                    $end_time = $article['g_endtime'] + $end_time;
                }else{
                    $end_time = time() + $end_time;
                }
                $update = ['g_endtime'=>$end_time,'is_g_top'=>1];
            }elseif ($result['city_type']=='2')
            {
                $num = Db::name('config')->where('id',35)->value('value');

                $count = Db::name('user_business')->where('is_s_top',1)->count();

                if ($count >=$num)
                {
                    $this->error('置顶位置不足');
                }
                if ($count >=$num)
                {
                    $this->error('置顶位置不足');
                }
                if ($type=='1')
                {
                    $money = $result['price'];
                    $this->error('暂未开放');
                }elseif($type=='2'){
                    $score = $result['price'] * $refresh2;
                    if ($score > $this->auth->score)
                    {
                        $this->success('成功','积分不足');
                    }


                    Db::name('user')->where('id',$this->auth->id)->setDec('score',$score);
                }else{
                    $score =  $result['price'] /2 *  $refresh2;
                    $money =  $result['price'] /2;
                    if ($this->auth->score < $score)
                    {
                        $this->error('积分不足');
                    }
                    $this->error('暂未开放');


                    Db::name('user')->where('id',$this->auth->id)->setDec('score',$score);
                }


                if ($article['s_endtime'] != 0)
                {
                    $end_time = $article['s_endtime'] + $end_time;
                }else{
                    $end_time = time() + $end_time;
                }

                $update = ['s_endtime'=>$end_time,'is_s_top'=>1];
            }
            Db::name('user_business')->where('id',$article_id)->update($update);
            Db::commit();
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('成功',1);
    }

    // 商家列表
    public function homeBusiness()
    {
        $result  = Db::name('user_business')
            ->where(['status'=>'1','is_status'=>'1','is_g_top'=>1])
            ->order('updatetime desc')
            ->field('id,avatar,mobile,position,name,content')
            ->select();
        foreach ($result as $key=>$value)
        {
            if (empty($value['mobile']))
            {
                $result[$key]['mobile'] = '';
            }
            $result[$key]['km'] = 0;
        }
        $this->success('成功',$result);
    }

    // 商家详情
    public function busDetail()
    {
        $id = $this->request->post('id');
        if (!$id)
        {
            $this->error('缺少参数');
        }
        $result = Db::name('user_business')->where('id',$id)->find();
        $image = explode(',',$result['imgdetail']);
        $banner_image = explode(',',$result['banner_image']);
        $data = [];
        foreach ($image as $value)
        {
            $data[] = ['image'=>$value];
        }
        $data2 = [];
        foreach ($banner_image as $val)
        {
            $data2[] = ['image'=>$val];
        }
        $result['image'] =$data;
        $result['banner_image'] = $data2;
        $result['km'] = 0;
        Db::name('user_business')->where('id',$id)->setInc('num');
        $this->success('成功',$result);

    }

    public function getBannerMoney()
    {
        $type = $this->request->post('type');
        if (!$type)
        {
            $this->error('参数错误');
        }
        $result = Db::name('banner_price')->where('type',$type)->select();

        foreach ($result as $key=>$value)
        {
            $result[$key]['aaa'] = false;
        }

        $this->success('价格',$result);

    }

    // 购买轮播图
    public function buy_banner()
    {
        $user_id = $this->auth->id;
        $banner_id = $this->request->post('id');
        $price_id = $this->request->post('price_id');
        $type = $this->request->post('type');// 类型type 1=首页,2=商铺,3=信息
        $buy = Db::name('banner_buy')->where(['type'=>$type,'banner_id'=>$banner_id,'status'=>['in','0,1']])->find();
        if ($buy)
        {
            $this->error('已被购买');
        }


        Db::startTrans();
        try {
            $price = Db::name('banner_price')->where('id',$price_id)->find();
            $end_time = $price['long'] * 86400 + time();
            $order_id = uniqid();
            $data = [
                'order_id'=>$order_id,
                'banner_id'=>$banner_id,
                'price'=>$price['price'],
                'user_id'=>$user_id,
                'createtime'=>time(),
                'updatetime'=>time(),
                'end_time'=>$end_time,
                'type'=>$type,
                'long'=>$price['long'],
            ];
            Db::name('banner_buy')->insert($data);
            if ($type==1)
            {
                Db::name('banner')->where('id',$banner_id)->update(['type'=>'1','user_id'=>$user_id,'buy_time'=>time(),'end_time'=>$end_time,'banner_price_id'=>$price['long'],'update_time'=>time()]);
            }elseif ($type==2)
            {
                Db::name('banners_shop')->where('id',$banner_id)->update(['type'=>'1','user_id'=>$user_id,'buy_time'=>time(),'end_time'=>$end_time,'banner_price_id'=>$price['long'],'update_time'=>time()]);
            }else{
                Db::name('banners')->where('id',$banner_id)->update(['type'=>'1','user_id'=>$user_id,'buy_time'=>time(),'end_time'=>$end_time,'banner_price_id'=>$price['long'],'update_time'=>time()]);
            }
            Db::commit();
        }catch (Exception $e)
        {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $code = Db::name('config')->where('id',38)->value('value');
        $this->success('购买成功',$code);
    }



    // 轮播图购买记录
    public function buy_log()
    {
        $type = $this->request->post('type');// 类型type 1=首页,2=商铺,3=信息
        $status = $this->request->post('status');// 1=已购买·: 0=为购买
        $where = [];
        if ($status==1)
        {
            $where['a.status'] = '1';
        }else{
            $where['a.status'] = '0';
        }

        if (!$type)
        {
            $this->error('缺少参数');
        }
        $user_id =  $this->auth->id;
        $where['a.type'] = $type;
        if ($type==1)
        {
//            $result = Db::name('banner')->where('user_id',$user_id)->select();
            $result =  Db::name('banner_buy')->alias('a')
                ->join('banner b','a.banner_id=b.id')
                ->where('a.user_id',$user_id)
                ->where($where)
                ->field('b.id,b.image,a.type,a.createtime,b.ex_status,b.memo')
                ->select()
            ;
        }elseif ($type==2)
        {
            $result =  Db::name('banner_buy')->alias('a')
                ->join('banners_shop b','a.banner_id=b.id')
                ->where('a.user_id',$user_id)
                ->where($where)
                ->field('b.id,b.image,a.type,a.createtime,b.ex_status,b.memo')
                ->select()
            ;
        }else{
            $result =  Db::name('banner_buy')->alias('a')
                ->join('banners b','a.banner_id=b.id')
                ->where('a.user_id',$user_id)
                ->where($where)
                ->field('b.id,b.image,a.type,a.createtime,b.ex_status,b.memo')
                ->select()
            ;
        }
        foreach ($result as $key => $value)
        {
            $result[$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
        }
        $this->success('成功',$result);
    }

    public function money_log()
    {
        $result = Db::name('user_money_log')
            ->alias('a')
            ->join('user b','a.from_user_id=b.id','left')
            ->where('user_id',$this->auth->id)
            ->field('a.id,a.money,b.nickname,from_user_id,a.createtime')
            ->select();

        foreach ($result as $key => $value)
        {
            if ($value['from_user_id'])
            {

            }else{
                $result[$key]['nickname'] = '后台管理员';
            }
            $result[$key]['createtime'] = date('Y-m-d H:i:s',$value['createtime']);
        }
        $this->success('成功',$result);
    }

    // 编辑轮播图
    public function edit_banner()
    {
        $type = $this->request->post('type');// 类型type 1=首页,2=商铺,3=信息
        $banner_id = $this->request->post('banner_id');// 轮播图id
        $lb_type = $this->request->post('lb_type');// 轮播类型  1=商家,2=产品
        $image = $this->request->post('image');// 图片
        $shop_id = $this->request->post('shop_id');// 图片
        $user_id = $this->auth->id;
        if (!$type)
        {
            $this->error('缺少参数');
        }
        if ($lb_type ==1)
        {
            // 商家id
            $shop_id = $this->auth->shop_id;
        }


        $value = Db::name('config')->where('id',20)->value('value');
        $status = 1;
        if ($value==1)
        {
            $status=0;
        }
        if ($type==1)
        {
            Db::name('banner')->where('id',$banner_id)->update(['user_id'=>$user_id,'ex_status'=>$status,'update_time'=>time(),'image'=>$image,'type_url'=>$lb_type,'type_id'=>$shop_id]);
        }elseif ($type==2)
        {
            Db::name('banners_shop')->where('id',$banner_id)->update(['user_id'=>$user_id,'ex_status'=>$status,'update_time'=>time(),'image'=>$image,'type_url'=>$lb_type,'type_id'=>$shop_id]);
        }else{
            Db::name('banners')->where('id',$banner_id)->update(['user_id'=>$user_id,'ex_status'=>$status,'update_time'=>time(),'image'=>$image,'type_url'=>$lb_type,'type_id'=>$shop_id]);
        }

        $this->success('更新成功',1);

    }


    // 定时任务
    public function buy_update()
    {
       $result2  =  Db::name('banner_buy')->where('end_time','<',time())->select();
       $result1  =  Db::name('banner_buy')->where('status','0')->where('createtime','<',time()-3600)->select();
       $image = Db::name('config')->where('id',39)->value('value');
       if ($result1)
       {
           foreach ($result1 as $key => $value)
           {
               if ($value['type']==1)
               {
                   Db::name('banner')->where('id',$value['banner_id'])->update(['user_id'=>0,'update_time'=>time(),'image'=>$image,'type_url'=>'3','type_id'=>'0','type'=>'0']);
               }elseif ($value['type']==2)
               {
                   Db::name('banners_shop')->where('id',$value['banner_id'])->update(['user_id'=>0,'update_time'=>time(),'image'=>$image,'type_url'=>'3','type_id'=>'0','type'=>'0']);
               }else{
                   Db::name('banners')->where('id',$value['banner_id'])->update(['user_id'=>0,'update_time'=>time(),'image'=>$image,'type_url'=>'3','type_id'=>'0','type'=>'0']);
               }
           }
       }
        if ($result2)
        {
            foreach ($result2 as $key => $value)
            {
                if ($value['type']==1)
                {
                    Db::name('banner')->where('id',$value['banner_id'])->update(['user_id'=>0,'update_time'=>time(),'image'=>$image,'type_url'=>'3','type_id'=>'0','type'=>'0']);
                }elseif ($value['type']==2)
                {
                    Db::name('banners_shop')->where('id',$value['banner_id'])->update(['user_id'=>0,'update_time'=>time(),'image'=>$image,'type_url'=>'3','type_id'=>'0','type'=>'0']);
                }else{
                    Db::name('banners')->where('id',$value['banner_id'])->update(['user_id'=>0,'update_time'=>time(),'image'=>$image,'type_url'=>'3','type_id'=>'0','type'=>'0']);
                }
            }
        }

        $this->success('成功',1);
    }


    public function share()
    {
        if ($this->auth->id)
        {
            $num = Db::name('user_score_log')->where('user_id',$this->auth->id)->whereTime('createtime','today')->where('memo','每日分享获得积分')->count();

            $score= Db::name('config')->where('id',40)->value('value');
            $num2= Db::name('config')->where('id',41)->value('value');
            if ($num <$num2)
            {
                Db::name('user_score_log')->insert(['user_id'=>$this->auth->id,'score'=>$score,'before'=>$this->auth->score,'after'=>$this->auth->score+ $score,'createtime'=>time(),'memo'=>'每日分享获得积分']);
                Db::name('user')->where('id',$this->auth->id)->setInc('score',$score);
            }
        }
    }
}
